package org.tech4j.edi.base.retry;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.tech4j.common.spi.Join;
import org.tech4j.edi.api.factory.RetryHandleFactory;
import org.tech4j.edi.common.RetryHandle;

import java.util.List;
import java.util.Map;

/**
 * @program: tech4j
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/7 21:43
 **/
@Join
public class DefaultRetryHandleFactory implements RetryHandleFactory {

    private final static Map<String, RetryHandle> RETRY_HANDLE_MAP = Maps.newConcurrentMap();

    /**
     * 注册处理器
     * @param bizType
     * @param retryHandle
     */
    public synchronized void registerHandle(final String bizType, final RetryHandle retryHandle) {
        RetryHandle existedRetryHandle = RETRY_HANDLE_MAP.get(bizType);
        if (existedRetryHandle != null) {
            throw new IllegalArgumentException("RetryHandle already exists for bizType: " + bizType);
        }
        RETRY_HANDLE_MAP.put(bizType, retryHandle);
    }

    public RetryHandle getRetryHandle(final String bizType) {
        // 这里可能存在一个问题
        /*
        如果当前RetryHandle存在事务问题，那么此时事务会失效，因为RetryHandle并不是从Spring 容器中获取的
        所以，这里需要引入ApplicationContext，从Spring容器中获取RetryHandle
         */
        RetryHandle retryHandle = RETRY_HANDLE_MAP.get(bizType);
        if (retryHandle == null) {
            throw new IllegalArgumentException("RetryHandle not found for bizType: " + bizType);
        }
        return retryHandle;
    }

    @Override
    public List<String> getRetryType() {
        return Lists.newArrayList(RETRY_HANDLE_MAP.keySet());
    }
}
